Page({
  data: {
    words:[],
    currentIndex: 0,
    currentWord: {wordId: 0, word: "", chinese: "", sent: ""},
    favorites:{},
    letters:['A','B','C','D'],
    isImageChange:false,
    isHotChange:false,
    imageSrc1:'/pages/img/887cdff6f914426f92d5d49407414eb2.png',
    imageSrc2:'/pages/img/00788e60b9304b8bb173db45508c2db7.png',
    clickCount:0,
  },
  nextWord:function(){
    const mainPage = getCurrentPages().find(page => page.route === 'pages/main1/main1')
      if(mainPage){
        mainPage.setData({
          finishLen:this.data.currentIndex+1,
        })
      }
    let newIndex=(this.data.currentIndex+1);
    if(newIndex==this.data.words.length){
        wx.showToast({
          title: '已背完全部单词',
          icon:'success',
          duration:1500
        });
        wx.request({
          url: `http://81.70.199.174:8081/user/updateProgress?addWords=${this.data.words.length}`,
          method:'PATCH',
          header:{
            'Authorization':getApp().globalData.token,
          },
          success:(res)=>{
            console.log("更新进度成功");
          }
        })
        setTimeout(()=>{
          wx.switchTab({  
            url: '/pages/main1/main1',
          });
        },1500);
    }
    this.setData({
      currentIndex:newIndex,
      currentWord:this.data.words[newIndex]
    });
  },
  onLoad: function() {
    wx.request({
      url: 'http://81.70.199.174:8081/word/getNew',
      method: 'GET',
      header: {
        'Authorization': getApp().globalData.token,
      },
      success: (res) => {
        console.log('API响应:', res);
        if(res.data.code === 200 && res.data.data) {
          this.setData({
            words: res.data.data,
            currentWord: res.data.data[0]
          }, () => {
            this.setData({
              options: this.generateOptions1(0)
            });
          });
          const app=getApp();
          app.globalData.curwords=res.data.data;
        } else {
          wx.showToast({
            title: res.data.message || '获取单词失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求错误:', err);
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },
  goTo: function() {
    getApp().globalData.currentWord = this.data.currentWord;
    wx.navigateTo({url: '/pages/detail/detail'});
    wx.showToast({
      title: '查看详情',
      icon:'loading',
      duration:500
    })
  },
  generateOptions1:function(index){
    const correct=this.data.words[index];
    const option=[correct];
    const usedI=new Set([index]);
    for(let i=0;i<3;i++){
      let randomIndex;
      do{
        randomIndex=Math.floor(Math.random()*this.data.words.length);
      }while(usedI.has(randomIndex));
      option.push(this.data.words[randomIndex]);
      usedI.add(randomIndex);
    }
    return option.sort(()=>(Math.random()-0.5));
  },
  changePage:function(){
    setTimeout(()=>{
      this.nextWord();
      this.setData({
        selectedIndex:null,
        options:this.generateOptions1(this.data.currentIndex),
        isImageChange:false,
        isHotChange:false,
        clickCount:0,
      });
    },500);
    wx.showToast({ 
      title:'下一个',
      icon:'loading',
      duration:500
    });
  },
  selectOption1:function(e){
    const selectedIndex=e.currentTarget.dataset.index;
    const isCorrect=this.data.options[selectedIndex].chinese===this.data.currentWord.chinese;
    console.log(isCorrect);
    this.setData({
      selectedIndex,
      isCorrect
    });
    if(isCorrect){
      setTimeout(()=>{
        this.nextWord();
        const app=getApp();
        this.setData({
          selectedIndex:null,
          options:this.generateOptions1(this.data.currentIndex),
          isImageChange:false,
        });
      },1000);
      wx.showToast({ 
        title:'Accept',
        icon:'success',
        duration:500
      });
      this.markWord();
    }else{
      wx.showToast({
        title:'Wrong Answer',
        icon:'error'
      });
    }
  },
  addFavorite:function(){
    const word1=this.data.currentWord;
    let favorites=getApp().globalData.favorites;
    if(this.data.isImageChange){
      wx.showToast({
        title: '已收藏过了',
        icon:'success',
        duration:500
      });
    }else{
      this.setData({isImageChange:true})
      favorites.push(word1);
      console.log(word1);
      wx.showToast({
        title: '收藏成功',
        icon:'success'
      });
      console.log(favorites);
    }
    wx.setStorageSync('favorites', favorites);
    const app = getApp();
    app.globalData.favorites = favorites;
    wx.setStorageSync('favorites', favorites);
    const mainPage = getCurrentPages().find(page => page.route === 'pages/main1/main1')
    if(mainPage){
      mainPage.setData({
        reviewlen:Object.keys(app.globalData.favorites).length
      })
    }
  },
  markWord: function() {
    wx.request({
        url: `http://81.70.199.174:8081/word/mark?wordId=${this.data.currentWord.wordId}`,
        method: 'POST',
        header: { 
            'Authorization': getApp().globalData.token,
        },
        data: {
            wordId: this.data.currentWord.wordId
        },
        
        fail: (err) => {
            console.log(err);
            wx.showToast({ title: '网络错误', icon: 'none' });
        }
    });
  },
})